package com.smartfactory.sail.config;

import com.ada.base.common.ApiResponse;
import com.smartfactory.sail.constant.header.HeaderBase;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractMappingJacksonResponseBodyAdvice;

import java.util.*;

@RestControllerAdvice
public class HeaderControllerAdvice extends AbstractMappingJacksonResponseBodyAdvice {
    @Override
    protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
        //TODO getMethod() maybe null
        if (returnType.getMethod().isAnnotationPresent(HeaderWrapper.class)) {
            List<Map<String, String>> header = new ArrayList<>();
            HeaderWrapper headerWrapper = returnType.getMethod().getAnnotation(HeaderWrapper.class);
            Class<? extends HeaderBase> headerBaseClass = headerWrapper.value();
            Arrays.stream(headerBaseClass.getEnumConstants()).forEach(o -> addMap(header, o.getKey(), o.getValue()));
            Object value = bodyContainer.getValue();
            if (value instanceof ApiResponse)
                ((ApiResponse) value).setHeader(header);
        }
    }

    private void addMap(List<Map<String, String>> data, String key, String value) {
        if (data == null)
            data = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("label", value);
        map.put("prop", key);
        data.add(map);
    }
}
